package com.varian.system.service.impl;

import cn.hutool.core.lang.Assert;
import com.varian.security.util.SecurityUtil;
import com.varian.system.constant.SystemConstant;
import com.varian.system.dto.UserNoticeListDTO;
import com.varian.system.mapper.UserNoticeMapper;
import com.varian.system.service.IUserNoticeService;
import com.varian.system.vo.UserNoticeVO;
import com.varian.tool.exception.BizException;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @author ben
 * @since 2024/9/19
 */
@Service
@RequiredArgsConstructor
public class UserNoticeServiceImpl implements IUserNoticeService {

    private final UserNoticeMapper baseMapper;

    @Override
    public List<UserNoticeVO> list(UserNoticeListDTO dto) {
        return baseMapper.selectListBy(dto, SecurityUtil.getUserId());
    }

    @Override
    public UserNoticeVO detail(Long noticeId) {
        UserNoticeVO vo = baseMapper.selectByNoticeId(noticeId, SecurityUtil.getUserId());
        Assert.notNull(vo, () -> BizException.of(SystemConstant.NOTICE_NOT_EXIST));
        if (!vo.getReadStatus().equals(Boolean.TRUE)) {
            vo.setReadStatus(Boolean.TRUE).setReadTime(LocalDateTime.now());
            baseMapper.updateReadStatusByNoticeId(noticeId, vo.getReadTime());
        }
        return vo;
    }

    @Override
    public boolean readAll() {
        baseMapper.updateReadStatusByUserId(SecurityUtil.getUserId(), LocalDateTime.now());
        return true;
    }

    @Override
    public boolean read(Long noticeId) {
        UserNoticeVO vo = baseMapper.selectByNoticeId(noticeId, SecurityUtil.getUserId());
        Assert.notNull(vo, () -> BizException.of(SystemConstant.NOTICE_NOT_EXIST));
        baseMapper.updateReadStatusByNoticeId(noticeId, LocalDateTime.now());
        return true;
    }
}
